﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using Kiiro.Common.Entities;
using Kiiro.Common.Utility;
using Kiiro.Model;
using Kiiro.SiteDefinition.ControlTemplates;
using Kiiro.SiteDefinition.Core;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace Kiiro.SiteDefinition.ProjectPages
{
    public partial class NewDiscussion : BasePage
    {
        #region Properties
        public Discussion Discussion
        {
            get;
            set;
        }

        public CustomFieldCollection CustomFields
        {
            get { return ( CustomFieldCollection ) v2CustomFieldCollection; }
        }

        public TeamMemberCollection TeamMembers
        {
            get { return ( TeamMemberCollection ) teamMembers; }
        }

        public AttachmentControl Attachments
        {
            get { return ( AttachmentControl ) attachmentControl; }
        }

        public NavigationSub NavigationSub
        {
            get { return KiiroMaster.NavigationSub; }
        }

        public FormButtons Buttons
        {
            get { return ( FormButtons ) v2FormButtons; }
        }

        public WMDEditor WMDTextEditor
        {
            get { return (WMDEditor) v2WMDEditor; }
        }
        #endregion

        #region Page Events
        protected override void OnInit ( EventArgs e )
        {
            base.OnInit ( e );

            CustomFields.ControlMode = SPControlMode.New;
            Buttons.SaveButton.ControlMode = SPControlMode.New;
            Buttons.CancelButton.ControlMode = SPControlMode.New;
            WMDTextEditor.DisplayMode = SPControlMode.New;
        }

        protected void Page_Load ( object sender, EventArgs e )
        {
            CustomFields.EntityType = typeof ( Discussion );
            CustomFields.Title = "Additional Information";

            SPContext context = CustomModel.GetCustomFieldsContext ( typeof ( Discussion ), 0, Context, SiteCollectionId, ServerRelativeUrl );
            context.FormContext.FormMode = SPControlMode.New;

            Buttons.SaveButton.ItemContext = context;
            Buttons.SaveButton.RenderContext = context;

            Buttons.CancelButton.ItemContext = context;
            Buttons.CancelButton.RenderContext = context;
            Buttons.CancelButton.RedirectUrl = Cancel ( );

            litTitle.Text = "New Discussion";

            if ( KiiroMaster.V2Header.Project != null && !string.IsNullOrEmpty ( KiiroMaster.V2Header.Project.Title ) )
            {
                litTitle.Text = KiiroMaster.V2Header.Project.Title + " - New Discussion";
            }

            if ( !Page.IsPostBack )
            {
                Setup setup = SetupModel.GetMidoriSetup ( SiteCollectionId, ServerRelativeUrl );

                if ( setup != null && setup.SendEmailUpdates )
                {
                    LoadTeamMembers ( );
                }
                else
                {
                    divEmail.Visible = false;
                    divDetails.Attributes.Add ( "class", "row borderless" );
                }

                if ( Request.UrlReferrer != null && Request.UrlReferrer.OriginalString != null &&
                    ( Request.UrlReferrer.OriginalString.Contains ( Constants.ProjectFileUrls.DiscussionsAll )
                     || Request.UrlReferrer.OriginalString.Contains ( Constants.ProjectFileUrls.DiscussionDisplay ) )
                    )
                {
                    lnkBack.NavigateUrl = Request.UrlReferrer.OriginalString;
                    pnlActionBar.Visible = true;
                }
            }
        }
        #endregion

        internal override string Cancel ( )
        {
            return string.Format ( "{0}{1}", ServerRelativeUrl, Constants.ProjectFileUrls.DiscussionsAll );
        }

        internal override bool Save ( )
        {
            if ( PermissionBitsDiscussions [ 0 ] )
            {
                Discussion = new Discussion ( );
                Discussion.ModifiedBy = CurrentUser;
                Discussion.ModifiedDate = DateTime.Now;
                Discussion.CreatedBy = CurrentUser;
                Discussion.CreatedDate = DateTime.Now;
                Discussion.ServerRelativeUrl = ServerRelativeUrl.Length > 1 ? ServerRelativeUrl : "/";
                Discussion.SiteCollectionId = SiteCollectionId;

                Discussion.Title = txtDiscussionTitle.Text;
                                
                Discussion.Text = WMDTextEditor.Markdown;
                Discussion.HTMLText = WMDTextEditor.Html;

                Discussion.UsersToNotify = TeamMembers.GetSelectedIds ( );
                Discussion.AttachmentList = Attachments.GetAttachments ( );
                Discussion.CustomFieldNamesAndValues = CustomFields.HarvestCustomFieldValues ( );

                Discussion.EditType = EditType.Created;


                Discussion.AttachmentList = Attachments.ValidateFileExtension(Discussion.AttachmentList);

                Discussion = DiscussionModel.Save(Discussion, SiteCollectionId, ServerRelativeUrl);
                
                if ( Discussion.IsValid ( ))
                    Response.Redirect ( Cancel ( ) );
                else
                    PopulateErrorMessages ( );
            }
            else
            {
                Response.Redirect ( Cancel ( ) );
            }
            return true;
        }

        private void LoadTeamMembers ( )
        {
            TeamMemberCollection teamCollection = ( TeamMemberCollection ) TeamMembers;
            teamCollection.TeamMembers = TeamModel.GetTeamMembers ( SiteCollectionId, ServerRelativeUrl );
            teamCollection.ReadOnly = false;
        }

        private void PopulateErrorMessages ( )
        {
            lblDiscussionTextMessage.Text = FormattingHelpers.GetErrorMessageText ( Discussion.TextMessage );
            lblDiscussionTitleMessage.Text = FormattingHelpers.GetErrorMessageText ( Discussion.TitleMessage );
            Attachments.ValidationMessage = FormattingHelpers.GetErrorMessageText(Discussion.AttachmentListMessage);
        }
    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.SiteDefinition/12/TEMPLATE/FEATURES/Kiiro.ProjectPages/Discussions/NewDiscussions.aspx.cs $
 * 
 * 18    2/08/10 2:28p Camerons
 * 
 * 17    1/13/10 6:15p Camerons
 * 
 * 16    1/11/10 11:51a Camerons
 * 
 * 15    1/06/10 12:39p Camerons
 * 
 * 14    12/14/09 2:10p Shafia
 * attachments file extensions validation for discussions, tasks, and
 * issues
 * 
 * 13    26/11/09 2:23p Shafia
 * 
 * 12    24/11/09 10:55a Shafia
 * Discussion now stores the HTML format of the discussion text and uses
 * the WMD editor
 * 
 * 11    19/10/09 2:51p Shafia
 * 
 * 10    23/09/09 4:34p Shafia
 * implemented the new WelcomeMessagePanel user control on Projects,
 * Users, CustomLists, Work, Documents, and Discussions pages.
 * Links are being displayed based on PermissionsBits[Entity]
 * 
 * 9     17/08/09 11:07a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/